<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utg-8">
<title>药品领取</title>
</head>
<body>
<div class="panel panel-info">

    <div class="panel-heading">
        <h3 class="panel-title">药品领取</h3>
    </div>
    
    <div  class="panel-body">
    
			<div class="form-group">
				<select id="employee_select" class="form-control">
				</select>
			</div>

			<div id="scan">
				
				<component :is="item.component" :text="item.text" v-for="(item,index) in items" 
				:index="index" :isscan="isScan" :key="index" @relayout="reLayout"></component>
				<div v-show="isScan" class="form-group" >
					<input   @keyup.enter="enter" v-model="traceCode"
						class="form-control" type="text" placeholder="请扫描药品追溯码    （tips:未上架：整箱出应扫箱子两下，按盒出：先扫箱子再扫盒子；已上架：只扫盒子一下）" />
					<table id="medicine_take_table"></table>
				</div>
				
			</div>
		</div>
</div>
<div id="btn_div" v-show="isVisible" class="pull-right">
	<button type="button" class="btn btn-info" @click="back">返回</button>
	<button type="button" class="btn btn-info" @click="submit">提交</button>
</div>

</body>
<script type="text/javascript">

	//展示选中人员的任务列表
	var showTaskMedicineOfEmployee = function(){		
    	btnDiv.isVisible = false;
		var employeeId = $('#employee_select').val();
		$.ajax({
			url : '<%=request.getContextPath()%>/e/taskMedicine/'+employeeId,
			dataType:'json',
			success: function(result){
				main.clearItems();
				if(result.length == 0){
					main.addComponentNothing();
				}else{
					$.each(result,function(index,item){
						main.addComponent(item);
					});
				}
			}
		});
	};
	
	//JQuery select2插件，显示治疗与防疫人员
	$("#employee_select").change(function(){
		showTaskMedicineOfEmployee();
	});
	$("#employee_select").select2({
      ajax: {
        url: "<%=request.getContextPath()%>/e/cureEmployee/list",
        type:'GET',
        dataType: 'json',
        cache: true,
        processResults: function (data, params) {
      		var itemList = [];
            $.each(data, function(index, item){
            	itemList.push({id: item.id, text: item.name});
            });
        	return {
          		results : itemList,
          		pagination: {
              		more: false
            	}
         	};
      	}
      },
      placeholder:'请选择医疗/防疫员工',
      language: "zh-CN",
    });
    

	//Vue 组件：用于展示任务数据
    const taskMedicineComponent = Vue.extend({
    	props:['text','index','isscan'],
    	template:'<ul class="list-group ">'+
				'<li class="list-group-item list-group-item-success">{{text.taskType+"-"+text.taskId}}<button v-show="!isscan" @click="scanMedicine" class="btn pull-right btn-info">出药</button></li>'+
				'<li class="list-group-item" v-for="(item,index) of text.medicineItems" :key="index">'+
				'<span class="text-primary">{{item.name}}</span>'+
				'<span class="badge">{{"已领："+item.takeQuantity+" "+item.unit}}</span>'+
				'<span class="badge">{{item.quantity+" "+item.unit}}</span>'+
				'</li>'+
			'</ul>',
		methods:{
			scanMedicine : function(){
				
				this.$emit('relayout',this.index);
			}
		}
    });
    //Vue 模板：无任务提示Vue组件
    const noTaskMedicineComponent = Vue.extend({
    	props:['text'],
    	template:'<div class="well well-lg">{{text}}</div>'
			
    });
    
    //主要Vue模块：包含了任务领取功能流程代码，详细流程图见图
    var main = new Vue({
    	el : "#scan",
    	data:{
    		traceCode : '',
    		items:[],
    		isScan:false,
    		preTraceCode:''
    	},
    	components:{
    		taskMedicineComponent,
    		noTaskMedicineComponent
    	},
    	methods: {
    		enter : function(event){
    			if(this.traceCode.replace(/\D/g, '').length <24){
    				speak('输入有误');
    				this.traceCode = '';
    				return ;
    			}
    			//去重
    			for(var i=0; i<medicineTakeData.length ; i++){
    				if( this.traceCode.indexOf(medicineTakeData[i].caseTraceCode)!=-1 || this.traceCode.indexOf(medicineTakeData[i].boxTraceCode)!=-1){
    					speak('药品已扫描');
    					this.traceCode = '';
    					return ;
    				}
    			}
    			//检查是否上架
    			$.ajax({
    				asyn : false,
    				url:'<%=request.getContextPath()%>/mt/putaway/check',
    				data:'boxTraceCode='+this.traceCode.substring(0, 24),
    				type:'post',
    				success:function(result){
    					//未上架
    					if(result.medicineId == null){
    						if(main.preTraceCode == ''){
    							main.preTraceCode = main.traceCode;
    							main.traceCode = '';
    						}else{
    							//检查是否入库
    							$.ajax({
    								asyn:false,
    								url : '<%=request.getContextPath()%>/mt/storage/check',
    								data:'caseTraceCode='+main.preTraceCode.substring(0, 24),
    								type:'post',
    								success:function(result){
    									if(result.caseTraceCode == null){
    										//未入库
    										main.preTraceCode = '';
    										main.traceCode ='';
    										speak('箱子无入库记录，请先入库');
    									}else if(result.caseTraceCode == "0"){
    										//入库，但已经被领取
    										main.preTraceCode = '';
    										main.traceCode = '';
    										speak('箱子已出库');
    									}else{
    										if(main.preTraceCode == main.traceCode){
    											//整箱出
    											main.traceCode ='';
    											main.preTraceCode = '';
    											showTakeRecord(result);
    										}else{
    											//箱子里的盒子
    											if(main.preTraceCode.substring(24) == main.traceCode.substring(24)){
    												var boxTraceCode = main.traceCode.substring(0,24);
    												result.boxTraceCode = boxTraceCode;
    												main.traceCode ='';
    												showTakeRecord(result);
    											}else{
    												main.preTraceCode = main.traceCode;
    												main.traceCode = '';
    											}
    										}
    									}
    								}
    							});
    						}
    					}else if(result.medicineId == 0){
    						//已上架，但已经被领取
    						main.traceCode = '';
    						speak('药品已出库');
    					}else{
    						//已上架，未被领取
    						main.traceCode = '';
    						showTakeRecord(result);
    					}
    		
    				}	
    			});
    		},
    		addComponent: function(taskMedicineItem){
    			this.items.push({component:'taskMedicineComponent', text:taskMedicineItem});
    		},
    		addComponentNothing: function(){
    			var name = $('#employee_select').find("option:selected").text(); 
    			speak(name+'无需领取药品');
    			this.items.push({component:'noTaskMedicineComponent', text:'该员工无需领取药品'});
    		},
    		clearItems : function(){
    			this.isScan = false;
    			this.items = [];
    		},
    		reLayout : function(index){
    			var item = this.items[index];
    			this.items = [];
    			this.items.push(item);
    			this.isScan = true;
    			btnDiv.isVisible = true;
    		}
    	}
    	
    });
    //按钮组绑定的Vue
    var btnDiv = new Vue({
    	el:"#btn_div",
    	data:{
    		isVisible : false
    	},
    	methods:{
    		back : function(){
   
    			showTaskMedicineOfEmployee();
    			clearTakeRecord();
    			
    		},
    		submit : function(){
    			if(medicineTakeData.length == 0){
    				speak('暂无可提交数据');
    				return ;
    			}
    			$.ajax({
    				url:'<%=request.getContextPath()%>/mt/saveRecords/'+employee.id+'/'+$("#employee_select").val()+'/'+main.items[0].text.taskId,
    				type:"post",
    				contentType:"application/json",
    				data:JSON.stringify(medicineTakeData),
    				success:function(){
    					speak('提交成功');
    					btnDiv.back();
    				}
    			});
    		}
    	}
    });
    //前台table展示与后台交互的数据
    var medicineTakeData = [];
    var showTakeRecord = function(data){
    	var medicineItems = main.items[0].text.medicineItems; 
    	for(var i=0; i< medicineItems.length; i++){
			//领取的药品要与药单上的匹配
			if(medicineItems[i].name == data.medicineName){
				//数量限制，统计已经领取的数量
				var count = 0;
				for(let i=0; i< medicineTakeData.length;i++){
					if(medicineTakeData[i].medicineName == data.medicineName){
						count++;
					}
				}
				//箱子、盒子限定
				if(medicineItems[i].unit == "箱"){
					if(data.boxTraceCode == null && data.caseTraceCode != null){
						;					
					}else{
						speak("单位不符合");
						return ;
					}
				}else{
					//不是整箱出，却扫描箱子
					if(data.boxTraceCode == null && data.caseTraceCode != null){
						speak('单位不符合');
						return ;
					}
				}
				//数量没超过
				if(count < (medicineItems[i].quantity-medicineItems[i].takeQuantity)){
					medicineTakeData.push(data);
					$("#medicine_take_table").bootstrapTable('refresh');
					speak('出库成功');
					break;
				}else{
					speak('药品数量已达药单上限');
					break;
				}
				
			}
    	}
    	if(i >= medicineItems.length){
    		speak('药单上没有该药品');
    	}
    }
    var clearTakeRecord = function(){
    	medicineTakeData = [];
    	main.preTraceCode = '';
    	$("#medicine_take_table").bootstrapTable('refresh');
    }
    
    //初始化bootstrap table
    $("#medicine_take_table").bootstrapTable({ // 对应table标签的id
	  method:"get",
      url: "<%=request.getContextPath()%>/m/nothing", // 获取表格数据的url，无实际意义
      cache: false, // 设置为 false 禁用 AJAX 数据缓存， 默认为true
      striped: true,  //表格显示条纹，默认为false
      pagination: true, // 在表格底部显示分页组件，默认false
      pageList: [10, 20, 30], // 设置页面可以显示的数据条数
      pageSize: 10, // 页面数据条数
      pageNumber: 1, // 首页页码
      sidePagination: 'client', // 设置为服务器端分页
      columns: [
      	{
              field: 'caseTraceCode', // 返回json数据中的name
              title: '箱子追溯码', // 表格表头显示文字
              align: 'center', // 左右居中
              valign: 'middle'// 上下居中
              
          },{
              field: 'boxTraceCode', // 返回json数据中的name
              title: '子追溯码', // 表格表头显示文字
              align: 'center', // 左右居中
              valign: 'middle'// 上下居中
              
          }, {
              field: 'medicineName',
              title: '药品名称',
              align: 'center',
              valign: 'middle'
          },{
              title: "操作",
              align: 'center',
              valign: 'middle',
              formatter: function (value, row, index) {
                  return '<button class="btn btn-default btn-sm" onclick="withdraw(\'' + index + '\')">撤回</button>';
              }
          }
      ],
      //注意：上面发的请求是无意义的，只是为了使用这个插件付出的代价
      //这里请求成功后返回本地要显示的数据，逆序显示
      responseHandler:function (res) {
                return medicineTakeData;
      },
})
//撤回操作
var withdraw = function(index){
	medicineTakeData.splice(index, 1);
	$("#medicine_take_table").bootstrapTable("refresh");
	speak('撤回成功');
}
</script>
</html>